package com.citrix.gs.util.base;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.citrix.gs.kit.PerforcePasswordEncryptor;
import com.citrix.gs.util.common.Config;
import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.core.file.FileSpecOpStatus;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.option.server.GetDepotFilesOptions;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;

public class PerforceUtil {
    
    
    private static Logger logger = LoggerFactory.getLogger(PerforceUtil.class);
    
    protected IOptionsServer perforceServer = null;
    
    public IOptionsServer getPerforceServer() {
        return perforceServer;
    }
    
    
    public boolean initConfigServer(String serverUri, String userName, String password) {
        
        // TODO: support not schema included in serverUri
        if(perforceServer != null) {
            releaseConfigServer();
        }
        
        try{
            perforceServer = ServerFactory.getOptionsServer(serverUri, null);
            if(perforceServer != null) {
                perforceServer.connect();
                perforceServer.setUserName(userName);
                perforceServer.login(password);
            } else {
                return false;
            }
            
        } catch(Exception e) {
            logger.error("Init config server fail: ", e);
            return false;
        }
        
        return true;
        
    }

    public boolean initConfigServer(){
        
        String serverUri = String.format("p4java://%s", Config.me().getProperty("platform.perforce.server"));
        String userName = Config.me().getProperty("platform.perforce.username");
        String password = PerforcePasswordEncryptor.instance().decryptString(Config.me().getProperty("platform.perforce.password"));
        
        return initConfigServer(serverUri, userName, password);
    }
    
    public Document getXmlAsDoc(String path) {
        
        Document doc = null;
        
        try {
            
            List<IFileSpec> fileList = perforceServer.getDepotFiles(
                    FileSpecBuilder.makeFileSpecList(path), new GetDepotFilesOptions());
            
            if(fileList != null && fileList.size() == 1 && fileList.get(0).getOpStatus() == FileSpecOpStatus.VALID) {
                
                SAXReader reader = new SAXReader();
                doc = reader.read(fileList.get(0).getContents(true));

                
            } else {
                logger.error("Xml file: {} could not be found", path);
            }
            
        } catch (P4JavaException e) {
            logger.error("Fail to get xml file: {}" , path, e);
        } catch (DocumentException e) {
            logger.error("Fail to read xml file");
        }
        
        return doc;
    }

    public boolean releaseConfigServer(){
        if(perforceServer != null) {
            try {
                perforceServer.disconnect();
            } catch (Exception e) {
                logger.error("Disconnect config server fail: ", e);
            }finally {
                perforceServer = null;
            }
        }
        return true;
    }
}
